import React, { useState, useEffect, useRef } from 'react';
import { 
  Card, 
  Typography, 
  Button, 
  Space, 
  Divider, 
  Row, 
  Col,
  Alert,
  Spin,
  message,
  Modal,
  Upload,
  Checkbox,
  Badge,
  Tooltip
} from 'antd';
import { 
  SettingOutlined, 
  PlusOutlined, 
  ReloadOutlined,
  ExportOutlined,
  ImportOutlined,
  SelectOutlined,
  CheckSquareOutlined
} from '@ant-design/icons';
import ModelConfigForm from '../../components/settings/ModelConfigForm';
import ModelStatusIndicator from '../../components/settings/ModelStatusIndicator';
import { useModelConfigStore } from '../../stores/model-config.store';
import { ModelConfigInfo } from '../../types/model-config';
import './style.css';

const { Title, Text, Paragraph } = Typography;

const ModelConfigPage: React.FC = () => {
  const [selectedConfig, setSelectedConfig] = useState<ModelConfigInfo | null>(null);
  const [showForm, setShowForm] = useState(false);
  const [batchMode, setBatchMode] = useState(false);
  const [selectedConfigIds, setSelectedConfigIds] = useState<Set<string>>(new Set());
  const [batchTesting, setBatchTesting] = useState(false);

  const {
    configs: modelConfigs,
    loading,
    error,
    testingConfigs,
    loadConfigs,
    loadTemplates,
    createConfig,
    updateConfig,
    deleteConfig,
    refreshConfigStatus,
    batchRefreshStatus,
    clearError,
    exportConfigs,
    importConfigs
  } = useModelConfigStore();

  useEffect(() => {
    loadConfigs();
    loadTemplates();
  }, [loadConfigs, loadTemplates]);

  useEffect(() => {
    if (error) {
      message.error(error);
      clearError();
    }
  }, [error, clearError]);

  // 定时健康检查 - 每10分钟自动检查一次所有激活的模型
  useEffect(() => {
    const checkInterval = 10 * 60 * 1000; // 10分钟
    
    // 立即执行一次健康检查
    const performHealthCheck = async () => {
      const activeConfigs = modelConfigs.filter(c => c.isActive);
      if (activeConfigs.length > 0) {
        console.log(`[Health Check] 检查 ${activeConfigs.length} 个激活的模型...`);
        for (const config of activeConfigs) {
          try {
            await refreshConfigStatus(config.id);
          } catch (error) {
            console.error(`[Health Check] 模型 ${config.displayName || config.modelName} 检查失败:`, error);
          }
        }
      }
    };

    // 页面加载后8分钟进行第一次检查
    const initialTimer = setTimeout(() => {
      performHealthCheck();
    }, 8 * 60 * 1000); // 8分钟

    // 设置定期检查
    const interval = setInterval(() => {
      performHealthCheck();
    }, checkInterval);

    return () => {
      clearTimeout(initialTimer);
      clearInterval(interval);
    };
  }, [modelConfigs, refreshConfigStatus]);

  const handleRefresh = async () => {
    await batchRefreshStatus();
    message.success('状态刷新完成');
  };

  const handleAddNew = () => {
    console.log('[DEBUG] handleAddNew - setting selectedConfig to null');
    setSelectedConfig(null);
    setShowForm(true);
  };

  const handleEditConfig = (config: ModelConfigInfo) => {
    setSelectedConfig(config);
    setShowForm(true);
  };

  const handleFormCancel = () => {
    setShowForm(false);
    setSelectedConfig(null);
  };

  const handleFormSubmit = async (values: any) => {
    try {
      console.log('[DEBUG] handleFormSubmit - selectedConfig:', selectedConfig);
      console.log('[DEBUG] handleFormSubmit - values:', values);
      
      if (selectedConfig) {
        console.log('[DEBUG] Calling updateConfig with ID:', selectedConfig.id);
        await updateConfig(selectedConfig.id, values);
        message.success('配置更新成功');
      } else {
        console.log('[DEBUG] Calling createConfig');
        await createConfig(values);
        message.success('配置创建成功');
      }
      setShowForm(false);
      setSelectedConfig(null);
    } catch (error) {
      console.error('Failed to save configuration:', error);
      message.error('保存配置失败');
    }
  };

  const handleDeleteConfig = async (configId: string) => {
    try {
      await deleteConfig(configId);
      message.success('配置删除成功');
    } catch (error) {
      console.error('Failed to delete configuration:', error);
      message.error('删除配置失败');
    }
  };

  const handleTestConfig = async (configId: string) => {
    await refreshConfigStatus(configId);
  };

  // 批量操作功能
  const handleBatchTest = async () => {
    if (selectedConfigIds.size === 0) {
      message.warning('请先选择要测试的配置');
      return;
    }
    
    setBatchTesting(true);
    const configIds = Array.from(selectedConfigIds);
    
    try {
      message.loading(`正在测试 ${configIds.length} 个配置...`, 0);
      
      for (const id of configIds) {
        await refreshConfigStatus(id);
      }
      
      message.destroy();
      message.success(`成功测试 ${configIds.length} 个配置`);
    } catch (error) {
      message.destroy();
      console.error('Batch test failed:', error);
      message.error('批量测试失败');
    } finally {
      setBatchTesting(false);
    }
  };

  const handleBatchDelete = async () => {
    if (selectedConfigIds.size === 0) {
      message.warning('请先选择要删除的配置');
      return;
    }
    
    Modal.confirm({
      title: '批量删除确认',
      content: `确定要删除选中的 ${selectedConfigIds.size} 个配置吗？此操作不可撤销。`,
      okText: '确认删除',
      cancelText: '取消',
      okButtonProps: { danger: true },
      onOk: async () => {
        try {
          const configIds = Array.from(selectedConfigIds);
          message.loading(`正在删除 ${configIds.length} 个配置...`, 0);
          
          for (const id of configIds) {
            await deleteConfig(id);
          }
          
          message.destroy();
          message.success(`成功删除 ${configIds.length} 个配置`);
          setSelectedConfigIds(new Set());
          setBatchMode(false);
        } catch (error) {
          message.destroy();
          console.error('Batch delete failed:', error);
          message.error('批量删除失败');
        }
      }
    });
  };

  const handleBatchActivate = async (activate: boolean) => {
    if (selectedConfigIds.size === 0) {
      message.warning('请先选择要操作的配置');
      return;
    }
    
    try {
      const configIds = Array.from(selectedConfigIds);
      message.loading(`正在${activate ? '启用' : '禁用'} ${configIds.length} 个配置...`, 0);
      
      for (const id of configIds) {
        const config = modelConfigs.find(c => c.id === id);
        if (config) {
          await updateConfig(id, { ...config, isActive: activate });
        }
      }
      
      message.destroy();
      message.success(`成功${activate ? '启用' : '禁用'} ${configIds.length} 个配置`);
    } catch (error) {
      message.destroy();
      console.error('Batch activate/deactivate failed:', error);
      message.error(`批量${activate ? '启用' : '禁用'}失败`);
    }
  };

  const toggleSelectConfig = (configId: string) => {
    const newSelected = new Set(selectedConfigIds);
    if (newSelected.has(configId)) {
      newSelected.delete(configId);
    } else {
      newSelected.add(configId);
    }
    setSelectedConfigIds(newSelected);
  };

  const selectAll = () => {
    setSelectedConfigIds(new Set(modelConfigs.map(c => c.id)));
  };

  const clearSelection = () => {
    setSelectedConfigIds(new Set());
  };

  const handleExportConfigs = async () => {
    try {
      const exportData = await exportConfigs();
      const blob = new Blob([exportData], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `model-configs-${new Date().toISOString().split('T')[0]}.json`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
      message.success('配置导出成功');
    } catch (error) {
      console.error('Export failed:', error);
      message.error('导出失败');
    }
  };

  const handleImportFile = (file: File) => {
    const reader = new FileReader();
    reader.onload = async (e) => {
      try {
        const content = e.target?.result as string;
        const result = await importConfigs(content);
        message.success(result || '配置导入成功');
        await loadConfigs();
      } catch (error) {
        message.error('导入失败：' + (error instanceof Error ? error.message : '未知错误'));
      }
    };
    reader.readAsText(file);
    return false;
  };

  const groupedConfigs = modelConfigs.reduce((groups, config) => {
    const { providerId } = config;
    if (!groups[providerId]) {
      groups[providerId] = [];
    }
    groups[providerId].push(config);
    return groups;
  }, {} as Record<string, ModelConfigInfo[]>);

  if (loading) {
    return (
      <div className="model-config-page">
        <div className="loading-container">
          <Spin size="large" />
          <Text className="loading-text">加载模型配置中...</Text>
        </div>
      </div>
    );
  }

  return (
    <div className="model-config-page">
      <div className="page-header">
        <div className="header-content">
          <div className="header-info">
            <Title level={2}>
              <SettingOutlined /> 模型配置管理
            </Title>
            <Paragraph>
              管理AI模型的配置参数，包括API端点、密钥和模型名称。
              支持多个提供商和同一提供商的多个模型配置。
            </Paragraph>
          </div>
          <div className="header-actions">
            <Space wrap>
              {batchMode ? (
                <>
                  <Badge count={selectedConfigIds.size} showZero>
                    <Button 
                      icon={<CheckSquareOutlined />}
                      onClick={selectAll}
                    >
                      全选
                    </Button>
                  </Badge>
                  <Button onClick={clearSelection}>
                    清空选择
                  </Button>
                  <Button 
                    type="primary"
                    icon={<ReloadOutlined />}
                    onClick={handleBatchTest}
                    loading={batchTesting}
                    disabled={selectedConfigIds.size === 0}
                  >
                    批量测试
                  </Button>
                  <Button 
                    onClick={() => handleBatchActivate(true)}
                    disabled={selectedConfigIds.size === 0}
                  >
                    批量启用
                  </Button>
                  <Button 
                    onClick={() => handleBatchActivate(false)}
                    disabled={selectedConfigIds.size === 0}
                  >
                    批量禁用
                  </Button>
                  <Button 
                    danger
                    onClick={handleBatchDelete}
                    disabled={selectedConfigIds.size === 0}
                  >
                    批量删除
                  </Button>
                  <Button 
                    onClick={() => {
                      setBatchMode(false);
                      setSelectedConfigIds(new Set());
                    }}
                  >
                    退出批量操作
                  </Button>
                </>
              ) : (
                <>
                  <Button 
                    icon={<SelectOutlined />}
                    onClick={() => setBatchMode(true)}
                    disabled={modelConfigs.length === 0}
                  >
                    批量操作
                  </Button>
                  <Button 
                    icon={<ReloadOutlined />} 
                    onClick={handleRefresh}
                    loading={loading}
                  >
                    刷新状态
                  </Button>
                  <Upload
                    accept=".json"
                    beforeUpload={handleImportFile}
                    showUploadList={false}
                  >
                    <Button 
                      icon={<ImportOutlined />}
                      disabled={loading}
                    >
                      导入配置
                    </Button>
                  </Upload>
                  <Button 
                    icon={<ExportOutlined />}
                    onClick={handleExportConfigs}
                    disabled={loading || modelConfigs.length === 0}
                  >
                    导出配置
                  </Button>
                  <Button 
                    type="primary" 
                    icon={<PlusOutlined />}
                    onClick={handleAddNew}
                  >
                    添加模型
                  </Button>
                </>
              )}
            </Space>
          </div>
        </div>
      </div>

      <Divider />

      <div className="config-content">
        {Object.keys(groupedConfigs).length === 0 ? (
          <Card className="empty-state">
            <div className="empty-content">
              <SettingOutlined className="empty-icon" />
              <Title level={3}>暂无模型配置</Title>
              <Text>点击"添加模型"按钮开始配置您的第一个AI模型</Text>
              <Button 
                type="primary" 
                icon={<PlusOutlined />}
                onClick={handleAddNew}
                className="empty-action"
              >
                添加模型
              </Button>
            </div>
          </Card>
        ) : (
          <Row gutter={[24, 24]}>
            {Object.entries(groupedConfigs).map(([providerId, configs]) => (
              <Col xs={24} sm={24} md={12} lg={8} xl={6} key={providerId}>
                <Card 
                  className="provider-card"
                  title={
                    <div className="provider-header">
                      <Text strong>{configs[0].providerName}</Text>
                      <Text type="secondary" className="provider-url">
                        {configs[0].baseUrl}
                      </Text>
                    </div>
                  }
                  extra={
                    <Button 
                      size="small" 
                      icon={<PlusOutlined />}
                      onClick={handleAddNew}
                    >
                      添加模型
                    </Button>
                  }
                >
                  <div className="model-list">
                    {configs.map((config) => (
                      <div 
                        key={config.id} 
                        className={`model-item ${batchMode ? 'batch-mode' : ''} ${selectedConfigIds.has(config.id) ? 'selected' : ''}`}
                        onClick={batchMode ? () => toggleSelectConfig(config.id) : undefined}
                        style={batchMode ? { cursor: 'pointer' } : undefined}
                      >
                        {batchMode && (
                          <Checkbox
                            checked={selectedConfigIds.has(config.id)}
                            onChange={() => toggleSelectConfig(config.id)}
                            className="batch-checkbox"
                            onClick={(e) => e.stopPropagation()}
                          />
                        )}
                        <div className="model-info">
                          <div className="model-name">
                            <Text strong>{config.displayName || config.modelName}</Text>
                            <ModelStatusIndicator 
                              status={testingConfigs.has(config.id) ? 'checking' : config.status}
                              lastChecked={config.lastChecked}
                              onTest={() => handleTestConfig(config.id)}
                              showTestButton={true}
                              responseTime={config.responseTime}
                              errorCount={config.errorCount}
                              uptime={config.uptime}
                              healthScore={config.healthScore}
                              lastError={config.lastError}
                              showDetails={true}
                              size="small"
                            />
                          </div>
                          <Text type="secondary" className="model-technical">
                            {config.modelName}
                          </Text>
                        </div>
                        {!batchMode && (
                          <div className="model-actions">
                            <Space size="small">
                              <Button 
                                size="small" 
                                onClick={() => handleEditConfig(config)}
                              >
                                编辑
                              </Button>
                              <Button 
                                size="small"
                                danger
                                onClick={() => handleDeleteConfig(config.id)}
                              >
                                删除
                              </Button>
                            </Space>
                          </div>
                        )}
                      </div>
                    ))}
                  </div>
                </Card>
              </Col>
            ))}
          </Row>
        )}

        {showForm && (
          <ModelConfigForm
            visible={showForm}
            config={selectedConfig}
            onCancel={handleFormCancel}
            onSubmit={handleFormSubmit}
            onSuccess={loadConfigs}  // 传递刷新回调
          />
        )}
      </div>

      <Alert
        message="提示"
        description="DeepSeek和Claude等模型支持同一base_url配置多个模型名称。配置保存后将立即在对话界面中生效。"
        type="info"
        showIcon
        closable
        className="page-info"
      />
    </div>
  );
};

export default ModelConfigPage;